package org.caijin.springzookeeper.Curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.caijin.springzookeeper.Id.OrderIdGenerator;

public class CuratorLockTest implements Runnable {
    public final static String cluster_connection = "192.168.88.100:2181,192.168.88.101:2181,192.168.88.102:2181";
    // 构建客户端
    final static CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(cluster_connection)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
    private OrderIdGenerator orderIdGenerator = new OrderIdGenerator();
    //可重入互斥锁
    final InterProcessMutex lock = new InterProcessMutex(client, "/lock");

    public static void main(String[] args) throws InterruptedException {
        client.start();
        for (int i = 0; i < 30; i++) {
            new Thread(new CuratorLockTest()).start();
        }
        Thread.currentThread().join();
    }

    @Override
    public void run() {
        try{
            lock.acquire();
            String orderId = orderIdGenerator.generateOrderId();
            System.out.println("生成订单号 "+orderId);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                lock.release();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
